import axios from 'axios';
import {message} from '@/assets/js/resetMessage';
import store from '@/store'

const http = axios.create({
    // 设置超时时间
    timeout: 43200000,
    baseURL: process.env.NODE_ENV === "development" ? '/api' : `${window.location.origin}/api`,
    // 其他axios的配置详见：https://www.kancloud.cn/yunye/axios/234845

});

// 添加请求拦截器
http.interceptors.request.use(
    config => {
        config.headers['token'] = `${window.localStorage.getItem('token')}`;
        config.params = {
            ...config.params,  // 保留原有的参数
            time: new Date().getTime(),  // 添加新的通用变量
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//响应拦截器
// 例子
// this.$接口名称(data2).then((result) => {
//     console.log(result);
// },err=>{
//     console.log(err)
//     console.log(123)
// })

http.interceptors.response.use(
    //为了解决没有code的时候，多了很多判断
    response => {
        store.state.loading = false;
        const res2 = response
        //正常的接口
        const res = response.data;
        if (res.code != 0 && res2.status != 200) {
            message({
                message: res.msg,
                type: 'error',
                duration: 3 * 1000
            })
            if (res.code == 401) {
                setTimeout(() => {
                    window.location = window.location.origin + window.location.pathname;
                }, 1000)
            }
            return Promise.reject(res);
        } else {
            if (res.code == 401) {
                message({
                    message: res.msg,
                    type: 'error',
                    duration: 3 * 1000
                })
                setTimeout(() => {
                    window.location = window.location.origin + window.location.pathname;
                }, 1000)
            }
            store.state.loading = false;
            if (res.code == 0) {
                return res
            } else if (res.code == undefined) {//处理返回值没有code的时候
                return res2.data
            } else {
                message({
                    message: res.msg,
                    type: 'error',
                    duration: 3 * 1000
                })
                return Promise.reject(res);
            }
        }
    },
    error => {
        console.log(error)
        //error.response.status状态码status
        message({
            message: error.msg,
            type: 'error',
            duration: 3 * 1000
        })
        if (error.response.status == 401) {
            window.location = window.location.origin + window.location.pathname;
        }
        return Promise.reject(error);
    }
);

export default http;

